package com.woniuxy.gobang.ui;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;

import dao.BattleDataDAO;
import dao.UserDataDAO;
import entity.Battle;
import entity.User;
import exception.DAOException;
import gobang_util.DbUtil;
import gobang_util.GobangUtil;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import messge.ExitMessage;
import messge.Message;
import messge.NewStartMessage;
import messge.PieceMessage;
import messge.RegretMessage;
import messge.WinMessage;

/**
 * 对战模式及功能
 * 
 * @author AC
 *
 */
public class FightModeStage extends Stage {
	// 棋盘边距
	private int margin;
	// 棋盘格子大小
	private int size;
	// 格子数
	private int cellCount;
	// 按键区域大小
	private int buttonArea;
	// 棋子半斤
	private int pieceRadius;
	// 记录落子情况
	private List<Piece> downPiece = new ArrayList<>();
	// 用于翻转棋子颜色的标志位
	private boolean colorFlag;
	// 游戏结束标志位
	private boolean gameOver = false;
	// 用于检测本次对局第一手棋颜色
	private boolean firstCheck = true;
	// 记录本局自己的颜色
	private Color ownColor;

	private Label lbTimer = new Label();
	private int maxTime = 20;
	private int seconds;
	private boolean timerFlag = false;

	private Pane pane = new Pane();

	private Timer timer;

	private Stage stage = this;

	public FightModeStage() {
		this.margin = 50;
		this.size = 40;
		this.cellCount = 15;
		this.buttonArea = 60;
		this.pieceRadius = 15;
		this.colorFlag = false;
		this.seconds = this.maxTime;

		lbTimer.setStyle(getFullScreenExitHint());
		lbTimer.setFont(Font.font(25));

		// 为窗体设置标题
		setTitle("蜗牛五子棋" + " " + "当前用户:" + Global.user.getAccount());
		// 设置窗体大小不可调整
		setResizable(false);
		// 创建面板

		// 设置背景颜色
		pane.setBackground(new Background(new BackgroundFill(Color.BLANCHEDALMOND, null, null)));
		// 调用绘制棋盘的方法
		drawChessBoard(pane);
		// 面板实现鼠标事件监听
		pane.setOnMouseClicked(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent event) {

				if (gameOver == true) {
					return;
				}
				// 限制落子区域
				if (event.getX() <= margin - size / 2 || event.getX() >= margin + cellCount * size + size / 2) {
					return;
				}
				// 限制落子区域
				if (event.getY() <= margin - size / 2 || event.getY() >= margin + cellCount * size + size / 2) {
					return;
				}

				int pieceX = (int) (((event.getX() + size / 2) - margin) / size);
				int pieceY = (int) (((event.getY() + size / 2) - margin) / size);
				try {
					drawChess(pieceX, pieceY, pane);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

		});

		this.setOnCloseRequest(new EventHandler<WindowEvent>() {
			@Override
			public void handle(WindowEvent event) {
				System.exit(0);
			}
		});

		lbTimer.setLayoutX(300);
		lbTimer.setLayoutY(10);
		pane.getChildren().add(lbTimer);

		// 创建一个场景对象
		Scene scene = new Scene(pane, margin * 2 + cellCount * size, margin * 2 + cellCount * size + buttonArea);// 控制窗体尺寸
		// 将场景添加到窗体上
		setScene(scene);

		// 将线条添加到面板
		show();
	}

	public void drawChess(int pieceX, int pieceY, Pane pane) throws IOException {
		// 检查是否落子 true为已落子
		for (Piece piece : downPiece) {
			if (piece.getX() == pieceX && piece.getY() == pieceY) {
				return;
			}
		}
		if (Global.notYourTurn) {
			return;
		}
		// 存储棋子颜色状态
		Color color = null;
		if (colorFlag) {
			color = Color.WHITE;
		} else {
			color = Color.BLACK;
		}
		// 创建圆对象
		Circle piece = new Circle();
		piece.setRadius(pieceRadius);
		// 设置背景颜色 根据标志位转换
		piece.setFill(color);
		// 添加棋子数据
		Piece pieceData = new Piece(pieceX, pieceY, color);
		downPiece.add(pieceData);
		this.timerFlag = false;
		Platform.runLater(() -> {
			lbTimer.setText("");
		});
		// 记录本局棋己方颜色
		if (firstCheck) {
			ownColor = color;
			firstCheck = false;
		}

		if (downPiece.size() == 16 * 16) {
			gameOver = true;
			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setContentText("平局");
			alert.show();
			GobangUtil.sendMessage(new WinMessage(WinMessage.DRAW_MESSEAGE));
			return;
		}

		piece.setCenterX(pieceX * this.size + this.margin);
		piece.setCenterY(pieceY * this.size + this.margin);

		pane.getChildren().add(piece);
		this.colorFlag = !this.colorFlag;

		// 输赢判断
		// 水平方向判断
		// 向左判断
		int pieceCount = 1;
		for (int x = pieceX - 1; x > pieceX - 5 && x >= 0; x--) {
			if (checkPiece(x, pieceY, color)) {
				pieceCount++;
			} else {
				break;
			}
		}

		for (int x = pieceX + 1; x < pieceX + 5 && x < 16; x++) {
			if (checkPiece(x, pieceY, color)) {
				pieceCount++;
			} else {
				break;
			}
		}

		printResult(pieceCount);

		// 垂直方向判断
		pieceCount = 1;
		// 向上判断
		for (int y = pieceY - 1; y > pieceY - 5 && y >= 0; y--) {
			if (checkPiece(pieceX, y, color)) {
				pieceCount++;
			} else {
				break;
			}
		}

		// 向下判断
		for (int y = pieceY + 1; y < pieceY + 5 && y < 16; y++) {
			if (checkPiece(pieceX, y, color)) {
				pieceCount++;
			} else {
				break;
			}
		}
		printResult(pieceCount);

		pieceCount = 1;
		// 左下
		int x = pieceX - 1;
		int y = pieceY + 1;
		while (x > pieceX - 5 && y < pieceY + 5 && x >= 0 && y <= 15) {
			if (checkPiece(x, y, color)) {
				pieceCount++;
			} else {
				break;
			}
			x--;
			y++;
		}
		// 右上
		x = pieceX + 1;
		y = pieceY - 1;
		while (x < pieceX + 5 && y > pieceY - 5 && y >= 0 && x <= 15) {
			if (checkPiece(x, y, color)) {
				pieceCount++;
			} else {
				break;
			}
			x++;
			y--;
		}
		printResult(pieceCount);

		pieceCount = 1;
		// 左上
		x = pieceX - 1;
		y = pieceY - 1;
		while (x > pieceX - 5 && y > pieceY - 5 && y >= 0 && x >= 0) {
			if (checkPiece(x, y, color)) {
				pieceCount++;
			} else {
				break;
			}
			x--;
			y--;
		}
		// 右下
		x = pieceX + 1;
		y = pieceY + 1;
		while (x < pieceX + 5 && y < pieceY + 5 && y <= 15 && x <= 15) {
			if (checkPiece(x, y, color)) {
				pieceCount++;
			} else {
				break;
			}
			x++;
			y++;
		}

		printResult(pieceCount);
		// 发送棋子信息给对方
		GobangUtil.sendMessage(new PieceMessage(pieceX, pieceY));

		Global.notYourTurn = true;

	}

	// 找是否有一个指定位置的棋子
	public boolean checkPiece(int pieceX, int pieceY, Color color) {
		for (Piece piece : downPiece) {
			if (piece.getX() == pieceX && piece.getY() == pieceY && piece.getColor().equals(color)) {
				return true;
			}
		}
		return false;
	}

	// 在打谱模式下绘制棋子
	public void hisDrawChess(int pieceX, int pieceY, Paint value, Pane pane) {
		// 创建圆对象
		Circle piece = new Circle();
		piece.setRadius(pieceRadius);
		piece.setFill(value);
		piece.setCenterX(pieceX * this.size + this.margin);
		piece.setCenterY(pieceY * this.size + this.margin);
		pane.getChildren().add(piece);

	}

	// 返回1 白方胜利 返回2黑方胜利 0没出现胜利
	public void printResult(int pieceCount) {
		if (pieceCount >= 5) {
			gameOver = true;
			if (!colorFlag) {
				Alert alert = new Alert(AlertType.INFORMATION);
				alert.setContentText("白方胜利");
				alert.show();
				// 发送结束给对方
				GobangUtil.sendMessage(new WinMessage(WinMessage.WIN_MESSEAGE_WHITE));
				return;
			} else {
				Alert alert = new Alert(AlertType.INFORMATION);
				alert.setContentText("黑方胜利");
				alert.show();
				GobangUtil.sendMessage(new WinMessage(WinMessage.WIN_MESSEAGE_BLACK));
				return;
			}
		}
	}

	public void drawChessBoard(Pane pane) {
		// 画出横线
		for (int i = 0; i < cellCount + 1; i++) {
			// 创建线条
			Line line = new Line(margin, margin + i * size, margin + cellCount * size, margin + i * size);
			// 将线条添加到面板
			pane.getChildren().add(line);
		}
		// 画出竖线
		for (int i = 0; i < cellCount + 1; i++) {
			// 创建线条
			Line line = new Line(margin + i * size, margin, margin + i * size, margin + cellCount * size);
			// 将线条添加到面板
			pane.getChildren().add(line);
		}

		// 创建新局按钮对象
		Button btnNew = new Button("新局");
		btnNew.setPrefSize(80, 50);
		btnNew.setLayoutX(50);
		btnNew.setLayoutY(670);
		pane.getChildren().add(btnNew);

		// 新局执行
		btnNew.setOnMouseClicked(new EventHandler<Event>() {

			@Override
			public void handle(Event event) {
				// 发起一个新局请求
				GobangUtil.sendMessage(new NewStartMessage(NewStartMessage.NEW_START_REQUEST));
			}
		});

		// 创建保存棋谱按钮对象
		Button btnSave = new Button("保存棋谱");
		btnSave.setPrefSize(80, 50);
		btnSave.setLayoutX(170);
		btnSave.setLayoutY(670);
		pane.getChildren().add(btnSave);
		// 保存棋谱执行
		btnSave.setOnMouseClicked(new EventHandler<Event>() {

			public void handle(Event event) {
				if (!gameOver) {
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setContentText("棋局未结束，无法保存");
					alert.show();
					return;
				}
				FileChooser fileChooser = new FileChooser();
				File file = fileChooser.showSaveDialog(stage);
				// 从List中读取棋子数据，将其写入file中，后缀为csv
				if (file == null) {
					return;
				}
				try {
					// 创建字符流
					BufferedWriter writer = new BufferedWriter(new FileWriter(file));
					for (Piece piece : downPiece) {
						String colorstr = null;
						if (piece.getColor().equals(Color.WHITE)) {
							colorstr = "white";
						} else if (piece.getColor().equals(Color.BLACK)) {
							colorstr = "black";
						}
						writer.write(piece.getX() + "," + piece.getY() + "," + colorstr);
						writer.newLine();
					}

					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		// 创建悔棋按钮对象
		Button btnRegret = new Button("悔棋");
		btnRegret.setPrefSize(80, 50);
		btnRegret.setLayoutX(290);
		btnRegret.setLayoutY(670);
		pane.getChildren().add(btnRegret);
		// 悔棋执行
		btnRegret.setOnMouseClicked(e -> {
			// 当有棋子时才能悔棋
			if (downPiece.size() > 0) {
				if (!Global.notYourTurn) {
					Alert alert = new Alert(AlertType.INFORMATION);
					// 设置提示框内容
					alert.setContentText("不是你的悔棋回合");
					// 设置提示框标题
					alert.setTitle("悔棋提示");
					// 展示弹框
					alert.show();
					return;
				}

				if (Global.regretTimes > 0) {
					// 发送一个悔棋请求
					RegretMessage regretMessage = new RegretMessage(RegretMessage.REGRET_REQUEST);
					GobangUtil.sendMessage(regretMessage);
					Global.regretTimes--;
				} else {
					Alert alert = new Alert(AlertType.INFORMATION);
					alert.setContentText("你的悔棋次数用完");
					alert.setTitle("悔棋提示");
					alert.show();
				}
			}
		});

		// 创建退出按钮对象
		Button btnExit = new Button("退出");
		btnExit.setPrefSize(80, 50);
		btnExit.setLayoutX(610);
		btnExit.setLayoutY(670);
		pane.getChildren().add(btnExit);
		// 退出执行
		btnExit.setOnMouseClicked(e -> {
			Alert alert = new Alert(AlertType.CONFIRMATION);
			// 设置提示框内容
			alert.setContentText("您确认退出吗?");
			// 设置提示框标题
			alert.setTitle("退出提示");
			// 展示弹框
			Optional<ButtonType> r = alert.showAndWait();
			if (r.get() == ButtonType.OK) {
				if (!gameOver) {
					// 给对方发送退出消息
					GobangUtil.sendMessage(new ExitMessage());
				}

				System.exit(0);
			}
		});

		// 创建读取记录按钮对象
		Button btnLoad = new Button("读取记录");
		btnLoad.setPrefSize(80, 50);
		btnLoad.setLayoutX(410);
		btnLoad.setLayoutY(670);
		pane.getChildren().add(btnLoad);

		btnLoad.setOnMouseClicked(e -> {
			new RecordStage();
		});

		// 修改密码
		Button btnModify = new Button("修改密码");
		btnModify.setPrefSize(80, 50);
		btnModify.setLayoutX(510);
		btnModify.setLayoutY(670);
		pane.getChildren().add(btnModify);

		btnModify.setOnMouseClicked(e -> {
			new ModifyPasswordStage();
		});

	}

	// 根据消息更新界面
	public void updateUI(Message message) throws SQLException {
		if (message instanceof PieceMessage) {
			Global.notYourTurn = false;
			this.timerFlag = true;
			PieceMessage pieceMessage = (PieceMessage) message;
			// 创建圆对象
			Circle piece = new Circle();
			// 设置圆的半径
			piece.setRadius(pieceRadius);

			// 定时器倒计时
			if (timer == null) {
				timer = new Timer();
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						if (timerFlag && (!gameOver)) {
							Platform.runLater(() -> {
								lbTimer.setText("倒计时:" + seconds);
							});
							seconds--;
							if (seconds == 0) {// 落子超时
								timerFlag = false;
								gameOver = true;
								if (ownColor == null || ownColor.equals(Color.WHITE)) {
									Platform.runLater(() -> {
										Alert alert = new Alert(AlertType.INFORMATION);
										alert.setContentText("黑方胜利");
										alert.show();
									});

									GobangUtil.sendMessage(new WinMessage(WinMessage.WIN_MESSEAGE_BLACK, true));
								} else {
									Platform.runLater(() -> {
										Alert alert = new Alert(AlertType.INFORMATION);
										alert.setContentText("白方胜利");
										alert.show();
									});
									GobangUtil.sendMessage(new WinMessage(WinMessage.WIN_MESSEAGE_WHITE, true));
								}
							}
						}
					}
				}, 0, 1000);
			}
			this.seconds = maxTime;
			// 设置圆背景颜色
			Piece pieceData = new Piece(pieceMessage.getX(), pieceMessage.getY(), Color.WHITE);
			if (colorFlag) {
				piece.setFill(Color.WHITE);
				pieceData.setColor(Color.WHITE);
			} else {
				piece.setFill(Color.BLACK);
				pieceData.setColor(Color.BLACK);
			}
			downPiece.add(pieceData);
			colorFlag = !colorFlag;
			// 设置原心坐标
			piece.setCenterX(pieceMessage.getX() * this.size + this.margin);
			piece.setCenterY(pieceMessage.getY() * this.size + this.margin);
			// 把圆添加到面板
			pane.getChildren().add(piece);
		} else if (message instanceof RegretMessage) {// 收到一个悔棋消息
			RegretMessage regretMessage = (RegretMessage) message;
			// 收到悔棋请求
			if (regretMessage.getFlag() == RegretMessage.REGRET_REQUEST) {
				// 弹出提示框
				Alert alert = new Alert(AlertType.CONFIRMATION);
				// 设置提示框内容
				alert.setContentText("对方请求悔棋，你同意吗?");
				// 设置提示框标题
				alert.setTitle("悔棋提示");
				// 展示弹框
				Optional<ButtonType> r = alert.showAndWait();
				// 同意悔棋
				if (r.get() == ButtonType.OK) {
					// 自己进行悔棋
					downPiece.remove(downPiece.size() - 1);
					pane.getChildren().remove(pane.getChildren().size() - 1);
					colorFlag = !colorFlag;
					// 对方悔棋后我方不能悔棋
					Global.notYourTurn = true;
					// 告诉对方可以悔棋
					timerFlag = false;
					RegretMessage regretMessage2 = new RegretMessage(RegretMessage.REGRET_AGREE);
					GobangUtil.sendMessage(regretMessage2);

				} else {// 不同意悔棋
					RegretMessage regretMessage2 = new RegretMessage(RegretMessage.REGRET_REFUSE);
					GobangUtil.sendMessage(regretMessage2);
				}
			} else if (regretMessage.getFlag() == RegretMessage.REGRET_AGREE) {// 收到同意悔棋
				timerFlag = false;
				downPiece.remove(downPiece.size() - 1);
				pane.getChildren().remove(pane.getChildren().size() - 1);
				colorFlag = !colorFlag;
				// 悔棋之后可以再下一次
				Global.notYourTurn = false;
			} else if (regretMessage.getFlag() == RegretMessage.REGRET_REFUSE) {// 收到拒绝悔棋
				Alert alert = new Alert(AlertType.INFORMATION);
				// 设置提示框内容
				alert.setContentText("对方不同意悔棋");
				// 设置提示框标题
				alert.setTitle("悔棋提示");
				// 展示弹框
				alert.show();
			}
		} else if (message instanceof NewStartMessage) {// 收到一个新局请求
			NewStartMessage newStartMessage = (NewStartMessage) message;
			// 收到新局请求
			if (newStartMessage.getFlag() == NewStartMessage.NEW_START_REQUEST) {
				// 弹出提示框
				Alert alert = new Alert(AlertType.CONFIRMATION);
				// 设置提示框内容
				alert.setContentText("对方希望开启新局，你同意吗?");
				// 设置提示框标题
				alert.setTitle("新局提示");
				// 展示弹框
				Optional<ButtonType> r = alert.showAndWait();
				// 如果同意新局
				if (r.get() == ButtonType.OK) {
					// 自己进行新局
					// 清空棋子节点
					pane.getChildren().removeIf(n -> n instanceof Circle);
					// 清空棋子数据
					downPiece.clear();
					colorFlag = false;
					gameOver = false;
					// 新局后都可以下棋
					Global.notYourTurn = false;
					// 重新检测本方颜色
					firstCheck = true;
					this.timerFlag = false;
					Platform.runLater(() -> {
						lbTimer.setText("");
					});
					// 告诉对方可以新局
					GobangUtil.sendMessage(new NewStartMessage(NewStartMessage.NEW_START_AGREE));

				} else {// 不同意新局
					GobangUtil.sendMessage(new NewStartMessage(NewStartMessage.NEW_START_REFUSE));
				}
			} else if (newStartMessage.getFlag() == NewStartMessage.NEW_START_REFUSE) {// 收到新局拒绝
				Alert alert = new Alert(AlertType.INFORMATION);
				// 设置提示框内容
				alert.setContentText("对方不同意新局");
				// 设置提示框标题
				alert.setTitle("新局提示");
				// 展示弹框
				alert.show();
			} else if (newStartMessage.getFlag() == NewStartMessage.NEW_START_AGREE) {// 同意新局
				// 清空棋子节点
				pane.getChildren().removeIf(n -> n instanceof Circle);
				// 清空棋子数据
				downPiece.clear();
				colorFlag = false;
				gameOver = false;
				// 新局后都可以下棋
				Global.notYourTurn = false;
				// 重新检测本方颜色
				firstCheck = true;
				this.timerFlag = false;
				Platform.runLater(() -> {
					lbTimer.setText("");
				});
			}
		} else if (message instanceof WinMessage) {// 如果收到一个胜负消息
			WinMessage winMessage = (WinMessage) message;
			if (winMessage.getFlag() == WinMessage.WIN_MESSEAGE_BLACK) {
				Alert alert = new Alert(AlertType.INFORMATION);
				alert.setContentText("黑方胜利");
				alert.show();
				gameOver = true;
				// 根据结果更新数据库
				MySQLUpdate(winMessage);
			} else if (winMessage.getFlag() == WinMessage.WIN_MESSEAGE_WHITE) {
				Alert alert = new Alert(AlertType.INFORMATION);
				alert.setContentText("白方胜利");
				alert.show();
				gameOver = true;
				// 根据结果更新数据库
				MySQLUpdate(winMessage);
			} else if (winMessage.getFlag() == WinMessage.DRAW_MESSEAGE) {
				Alert alert = new Alert(AlertType.INFORMATION);
				alert.setContentText("平局");
				alert.show();
				gameOver = true;
				// 根据结果更新数据库
				MySQLUpdate(winMessage);
			}
		} else if (message instanceof ExitMessage) {// 收到一个对方退出消息
			ExitMessage exitMessage = (ExitMessage) message;
			WinMessage winMessage = null;
			if (ownColor.equals(Color.WHITE)) {
				winMessage = new WinMessage(WinMessage.WIN_MESSEAGE_WHITE, true);
			} else {
				winMessage = new WinMessage(WinMessage.WIN_MESSEAGE_BLACK, true);
			}
			// 将对方的账户放进对象
			winMessage.setAccount(exitMessage.getAccount());
			winMessage.setId(exitMessage.getId());

			MySQLUpdate(winMessage);

			Alert alert = new Alert(AlertType.INFORMATION);
			alert.setContentText("对方退出，你获胜");
			Optional<ButtonType> r = alert.showAndWait();
			if (r.get() == ButtonType.OK) {
				System.exit(0);
			}

		}
	}

	private void MySQLUpdate(WinMessage winMessage) throws SQLException {
		Connection connect = DbUtil.getConnection();
		// 设置不自动提交
		connect.setAutoCommit(false);

		BattleDataDAO battledao = new BattleDataDAO();
		Battle battle = new Battle();
		UserDataDAO userdao = new UserDataDAO();

		if (ownColor.equals(Color.WHITE)) {
			battle.setWhiteAccount(Global.user.getAccount());
			battle.setBlackAccount(winMessage.getAccount());
		} else {
			battle.setWhiteAccount(winMessage.getAccount());
			battle.setBlackAccount(Global.user.getAccount());
		}

		battle.setResult(winMessage.getFlag());

		try {
			battledao.Insert(battle);// 添加对战结果
			if (winMessage.isReverse()) {
				User ownUser = userdao.selectAll(Global.user.getId());
				ownUser.setScore(ownUser.getScore() + 10);// 在原来的基础上减10分
				ownUser.setTotallTurnNum(ownUser.getTotallTurnNum() + 1);
				ownUser.setWinTimes(ownUser.getWinTimes() + 1);// 赢场加1
				// 更新数据
				userdao.update(ownUser, Global.user.getId());

				User otherUser = userdao.selectAll(winMessage.getId());// 得到原本数据
				otherUser.setScore(otherUser.getScore() - 10);// 在原来的基础上减10分
				otherUser.setFailedTimes(otherUser.getFailedTimes() + 1);// 输场加1
				otherUser.setTotallTurnNum(otherUser.getTotallTurnNum() + 1);
				// 更新数据
				userdao.update(otherUser, winMessage.getId());
			} else {
				// 己方数据修改
				User ownUser = userdao.selectAll(Global.user.getId());// 得到原本数据
				ownUser.setScore(ownUser.getScore() - 10);// 在原来的基础上减10分
				ownUser.setFailedTimes(ownUser.getFailedTimes() + 1);// 输场加1
				ownUser.setTotallTurnNum(ownUser.getTotallTurnNum() + 1);
				// 更新数据
				userdao.update(ownUser, Global.user.getId());
				// 对方数据修改
				User otherUser = userdao.selectAll(winMessage.getId());
				otherUser.setScore(otherUser.getScore() + 10);// 在原来的基础上减10分
				otherUser.setTotallTurnNum(otherUser.getTotallTurnNum() + 1);
				otherUser.setWinTimes(otherUser.getWinTimes() + 1);// 赢场加1
				// 更新数据
				userdao.update(otherUser, winMessage.getId());
			}

			connect.commit(); // 事务提交
		} catch (DAOException e) {
			e.printStackTrace();
			connect.rollback(); // 事务回滚
		} finally {
			DbUtil.closeAll(connect, null, null);
		}
	}
}
